package demo.jms.producer;

import java.io.Serializable;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import demo.entity.Email;

/**
 * 生产者
 * 
 * @author JSC
 *
 */
@Component("producerComponent")
public class ProducerComponent {
	@Resource(name = "jmsTemplate")
	private JmsTemplate jmsTemplate;
	/** jmsTemplate2才有配置邮件的消息转换器 */
	@Resource(name = "jmsTemplate2")
	private JmsTemplate jmsTemplate2;

	public void sendMessage(Destination destination, final String message) {
		System.out.println("[生产者发送了一条文本消息] " + message);
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(message);// 发送纯文本消息
			}
		});
	}

	public void sendMessage2(Destination destination, final Map<String, String> map) {
		System.out.println("[生产者发送了一条Map类型消息] " + map.get("message"));
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("message", map.get("message"));
				return mapMessage;// 发送Map类型消息
			}
		});
	}

	public void sendMessage3(Destination destination, final Serializable obj) {
		System.out.println("[生产者发送了一个邮件对象] " + obj.toString());
		
		// jmsTemplate.send(destination, new MessageCreator() {
		// public Message createMessage(Session session) throws JMSException {
		// return session.createObjectMessage(obj);// 邮件对象
		// }
		// });
		
		/* jmsTemplate2指定了消息转换器，上面的步骤写在EmailMessageConverter的toMessage方法 */
		jmsTemplate2.convertAndSend(destination, obj);
	}

}
